import axios from 'axios'
import store from '../store'
import { Dialog } from 'vant'

const service = axios.create({
  baseURL: '/api/',
  withCredentials: true,
  timeout: 30000
})
// var toast
// request拦截器
service.interceptors.request.use(
  config => {
    store.commit('app/showLoading')
    // toast = Toast.loading({ message: '加载中', forbidClick: true, duration: 0 })
    if (localStorage.getItem('authorization')) {
      config.headers['authorization'] = localStorage.getItem('authorization')
      config.headers['serviceType'] = 'phone'
    }
    return config
  },
  error => {
    store.commit('app/hideLoading')
    // toast.clear()
    // Do something with request error
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // toast.clear()
    store.commit('app/hideLoading')
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 101) {
        store.dispatch('user/logout').then(() => {
          location.reload()
        })
      } else if (res.code === 101) { // 身份过期
        // Notify({ type: 'warning', message: '身份已过期，请重新登录' })
        Dialog({ message: '身份已过期，请重新登录' })
        store.dispatch('user/logout').then(() => {
          location.reload()
        })
        return Promise.reject('error')
      } else {
        // Toast.fail(res.message)
        Dialog({ message: res.message })
        // Notify({ type: 'warning', message: res.message })
        return Promise.reject('error')
      }
    } else {
      return response.data
    }
  },
  error => {
    store.commit('app/hideLoading')
    // toast.clear()
    // Toast.fail('无法连接到本地代理程序，请确认代理程序是否运行正常！')
    Dialog({ message: '无法连接到本地代理程序，请确认代理程序是否运行正常！' })
    return Promise.reject(error)
  }
)

export default service
